package com.youlai.system.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.system.common.model.Option;
import com.youlai.system.common.result.PageResult;
import com.youlai.system.common.result.Result;
import com.youlai.system.model.form.MeasureForm;
import com.youlai.system.model.query.MeasurePageQuery;
import com.youlai.system.model.vo.MeasurePageVO;
import com.youlai.system.model.vo.MeasureScoreCountVO;
import com.youlai.system.plugin.dupsubmit.annotation.PreventDuplicateSubmit;
import com.youlai.system.service.SysMeasureService;
import com.youlai.system.service.SysScoreService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 整改措施控制器
 */
@Tag(name = "11.整改措施接口")
@RestController
@RequestMapping("/api/v1/measures")
@RequiredArgsConstructor
public class SysMeasureController {

    private final SysMeasureService measureService;

    private final SysScoreService scoreService;

    @Operation(summary = "整改措施分页列表")
    @GetMapping("/page")
    public PageResult<MeasurePageVO> getMeasurePage(
            @ParameterObject MeasurePageQuery queryParams
    ) {
        IPage<MeasurePageVO> result = measureService.getMeasurePage(queryParams);
        Map<Long, MeasureScoreCountVO> measureScoreCountMap = scoreService.getAllMeasureScoreCountMap();
        result.getRecords().forEach(measurePageVO -> {
            MeasureScoreCountVO measureScoreCountVO = measureScoreCountMap.get(measurePageVO.getId());
            if (measureScoreCountVO != null) {
                measurePageVO.setTotalCount(measureScoreCountVO.getTotalCount());
                measurePageVO.setSuccessCount(measureScoreCountVO.getSuccessCount());
                measurePageVO.setFailCount(measureScoreCountVO.getFailCount());
                measurePageVO.setSuccessRate(measureScoreCountVO.getSuccessRate());
            }
        });
        return PageResult.success(result);
    }

    @Operation(summary = "新增整改措施")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('sys:measure:add')")
    @PreventDuplicateSubmit
    public Result saveMeasure(
            @RequestBody @Valid MeasureForm measureForm
    ) {
        boolean result = measureService.saveMeasure(measureForm);
        return Result.judge(result);
    }

    @Operation(summary = "整改措施表单数据")
    @GetMapping("/{measureId}/form")
    public Result<MeasureForm> getMeasureForm(
            @Parameter(description = "整改措施ID") @PathVariable Long measureId
    ) {
        MeasureForm formData = measureService.getMeasureForm(measureId);
        return Result.success(formData);
    }


    @Operation(summary = "修改整改措施")
    @PutMapping(value = "/{measureId}")
    @PreAuthorize("@ss.hasPerm('sys:measure:edit')")
    public Result updateMeasure(
            @Parameter(description = "整改措施ID") @PathVariable Long measureId,
            @RequestBody @Validated MeasureForm measureForm) {
        boolean result = measureService.updateMeasure(measureId, measureForm);
        return Result.judge(result);
    }

    @Operation(summary = "删除整改措施")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:measure:delete')")
    public Result deleteMeasures(
            @Parameter(description = "整改措施ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "整改措施删除数据为空");
        List<Long> idList = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        boolean measureHasUsed = scoreService.measureHasUsed(idList);
        Assert.isTrue(!measureHasUsed, "整改措施使用中，不能被删除");
        boolean result = measureService.deleteMeasures(idList);
        return Result.judge(result);
    }

    @Operation(summary = "整改措施下拉列表")
    @GetMapping("/options")
    public Result<List<Option>> listMeasureOptions() {
        List<Option> list = measureService.listMeasureOptions();
        return Result.success(list);
    }

}
